package queuedemo;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 使用2个队列 来 实现栈
 */
class MyStack {

    private Queue<Integer> qu1;
    private Queue<Integer> qu2;

    public MyStack() {
        qu1 = new LinkedList<>();
        qu2 = new LinkedList<>();
    }
    
    public void push(int x) {
        if(!qu1.isEmpty()) {
            qu1.offer(x);
        }else if(!qu2.isEmpty()) {
            qu2.offer(x);
        }else {
            qu1.offer(x);
        }
    }
    
    public int pop() {
        if(empty()) {
            return -1;
        }
        if(!qu1.isEmpty()) {
            int size = qu1.size();
            while(size-1 != 0) {
                qu2.offer(qu1.poll());
                size--;
            }
            return qu1.poll();
        }else if(!qu2.isEmpty()) {
            int size = qu2.size();
            while(size-1 != 0) {
                qu1.offer(qu2.poll());
                size--;
            }
            return qu2.poll();
        }
        return -1;
    }
    
    public int top() {
        if(empty()) {
            return -1;
        }
        if(!qu1.isEmpty()) {
            int size = qu1.size();
            int tmp = -1;
            while(size != 0) {
                tmp = qu1.poll();
                qu2.offer(tmp);
                size--;
            }
            return tmp;
        }else if(!qu2.isEmpty()) {
            int size = qu2.size();
            int tmp = -1;
            while(size != 0) {
                tmp = qu2.poll();
                size--;
                qu1.offer(tmp);
            }
            return tmp;
        }
        return -1;
    }
    
    public boolean empty() {
        return qu1.isEmpty() && qu2.isEmpty();
    }
}